import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import moment from 'moment';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import {
  Row,
  Col,
  Card,
  Icon,
  Tooltip,
  Input,
  Spin,
  Pagination,
  Table,
  Drawer,
  Form,
  Select,
  Button,
  Switch,
  message,
  Modal,
} from 'antd';
import styles from './index.less';
import editImg from '@/assets/basic/customDictionary/xiazi.png';
import sy from '@/assets/basic/customDictionary/sy.png';
import bianji from '@/assets/basic/customDictionary/bianji.png';
import edit from '@/assets/basic/customDictionary/edit.png';
import moreImg from '@/assets/knowledge/more.png';
import qdbuttom from '@/assets/account/robotSetup/qdbuttom.png';
import qxbuttom from '@/assets/account/robotSetup/qxbuttom.png';
import append from '@/assets/account/roleManagement/append.png';
import query from '@/assets/account/authorization/query.png';
import relevance from '@/assets/account/roleManagement/relevance.png';
import RoleCheck from './roleCheck';
import AddRoles from './addRoles';

const Search = Input.Search;
const FormItem = Form.Item;
const { Option } = Select;

class RoleManagement extends Component {
  state = {
    list: [
      // { account: 'test@chatbot.cn', name: 'test', createTime: 1567499401305, id: '1', start: true },
      // { account: 'test@chatbot.cn', name: 'test', createTime: 1567499401305, id: '1', start: true },
      // { account: 'test@chatbot.cn', name: 'test', createTime: 1567499401305, id: '1', start: true },
      // { account: 'test@chatbot.cn', name: 'test', createTime: 1567499401305, id: '1', start: true },
      // { account: 'test@chatbot.cn', name: 'test', createTime: 1567499401305, id: '1', start: true },
      // { account: 'test@chatbot.cn', name: 'test', createTime: 1567499401305, id: '1', start: true },
      // { account: 'test@chatbot.cn', name: 'test', createTime: 1567499401305, id: '1', start: true },
      // { account: 'test@chatbot.cn', name: 'test', createTime: 1567499401305, id: '1', start: true },
      // { account: 'test@chatbot.cn', name: 'test', createTime: 1567499401305, id: '1', start: true },
      // { account: 'test@chatbot.cn', name: 'test', createTime: 1567499401305, id: '1', start: true },
      // { account: 'test@chatbot.cn', name: 'test', createTime: 1567499401305, id: '1', start: true },
      // { account: 'test@chatbot.cn', name: 'test', createTime: 1567499401305, id: '1', start: true },
    ],
    login: false,
    total: '12',
    current: 1,
    pageSize: 10,
    addModel: false,
    addModelRedact: null,
    startSetLIst: ['在线', '离线', '全部'],
    startSetone: null, // 状态
    startSettwo: null, // 创建人
    Redactobj: '', // 编辑角色传参对象值
    namelist: [],
  };

  componentDidMount() {
    const { dispatch } = this.props;
    this.newsysgetRolesByCreateUser();
  }

  unique5 = arr => {
    let x = new Set(arr);
    return [...x];
  };

  // 获取用户列表
  newsysgetRolesByCreateUser = () => {
    this.setState({ login: true });
    const { dispatch, currentUser } = this.props;
    const { pageSize, current, startSetone } = this.state;
    console.log(currentUser);
    let obj = {};
    if (startSetone === null || startSetone === 2) {
      obj = { createUserId: currentUser.uid, page: String(current), rows: String(pageSize) };
    } else {
      obj = {
        createUserId: currentUser.uid,
        page: String(current),
        rows: String(pageSize),
        uStatus: startSetone,
      };
    }

    // const userVo = {
    //   createUserId: currentUser.uid,
    //   page:current,
    //   rows:pageSize,
    //   uStatus: startSetone,
    // };
    setTimeout(() => {
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'roleManagement/getRoleByStatusOrCreateByPage',
          payload: obj,
          callback: res => {
            console.log(res);
            res.data.list.map(item => {
              item.status = item.userStatus === '0' ? false : true;
            });
            let namelist = [];
            res.data.list.map(item => {
              namelist.push(item.createUser);
            });
            //  this.unique5(namelist)
            this.setState({
              login: false,
              list: res.data.list,
              total: res.data.total,
              namelist: this.unique5(namelist),
            });
          },
        });
      });
    }, 100);
  };

  onChangeTable = a => {
    console.log(a);
    this.setState({ current: a }, () => {
      this.newsysgetRolesByCreateUser();
    });
  };

  onShowSizeChangeTable = (a, b) => {
    console.log(a, b);
    this.setState({ current: a, pageSize: b }, () => {
      this.newsysgetRolesByCreateUser();
    });
  };

  onClosebj = () => {
    this.setState({
      addModel: false,
    });
  };

  append = () => {
    this.setState({
      addModel: true,
      addModelRedact: '1',
    });
  };

  Redact = item => {
    console.log(item);
    this.setState({
      addModel: true,
      addModelRedact: '2',
      Redactobj: item,
    });
  };

  operation = () => {
    // console.log
  };

  ceshi = index => {
    const { current, pageSize } = this.state;
    let a = (current - 1) * pageSize + index + 1;
    return a;
  };

  // 下拉框
  handleChangeSelect = value => {
    console.log(`selected ${value}`);
    switch (value) {
      case '在线':
        this.setState({ startSetone: 1, current: 1 }, () => {
          // this.sysGetRoles();
        });
        break;
      case '离线':
        this.setState({ startSetone: 0, current: 1 }, () => {
          // this.sysGetRoles();
        });
        break;
      default:
        this.setState({ startSetone: 2, current: 1 }, () => {
          // this.sysGetRoles();
        });
        break;
    }
  };

  handleChangeState = value => {
    console.log(`selected ${value}`);
    this.setState({ startSettwo: value }, () => {
      // this.sysGetRoles();
    });
  };

  queryList = () => {
    // const { startSetone, startSettwo } = this.state;
    // console.log(startSetone,startSettwo)
    // if (startSetone || startSettwo) {
    //   this.sysGetRoles();
    // } else {
    //   this.newsysgetRolesByCreateUser();
    // }
    this.newsysgetRolesByCreateUser();
  };

  // 查询表单数据
  sysGetRoles = () => {
    this.setState({ login: true });
    const { startSetone, startSettwo } = this.state;
    const { dispatch, currentUser } = this.props;
    const roleVo = {
      createUserId: currentUser.uid,
      uStatus: startSetone,
      createUser: startSettwo,
    };
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'roleManagement/getRoleByStatusOrCreateBy',
        payload: roleVo,
        callback: res => {
          console.log('列表数据', res);
          res.data.map(item => {
            item.status = item.userStatus === '0' ? false : true;
          });
          this.setState({ login: false, list: res.data });
        },
      });
    });
  };

  rktbonChange = (item, index) => {
    console.log(item, index);
    if (item.roleName === 'admin') {
      message.info(`admin角色不可下线！`);
    } else {
      const { list } = this.state;
      list[index].status = !item.status;
      this.setState({ list }, () => {
        console.log(this.state.list);
      });
      this.setState({ login: true });
      const { dispatch, currentUser } = this.props;
      const roleVo = { userStatus: item.status ? 1 : 0, roleId: item.roleId };
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'roleManagement/sysUpdateRole',
          payload: roleVo,
          callback: res => {
            console.log('编辑角色', res);
            if (!res.code) {
              message.success(`${res.msg}`);
              this.newsysgetRolesByCreateUser();
            }
          },
        });
      });
    }
  };

  newSysDelRole = item => {
    // shareList
    const { dispatch, currentUser } = this.props;
    const { pageSize, current } = this.state;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'roleManagement/getUserByRoleId',
        payload: { roleId: item.roleId },
        callback: red => {
          console.log('判断该角色关联的用户列表', red.data.list);
          if (red.data.list.length) {
            Modal['confirm']({
              title: '删除角色',
              content: '此角色下有用户，是否确认删除？',
              okText: '删除',
              cancelText: '取消',
              onOk: () => {
                console.log(item);
                if (item.roleName === 'admin') {
                  message.info(`admin角色不可删除！`);
                } else {
                  this.setState({ login: true });
                  const roleVo = {
                    userId: currentUser.uid,
                    roleId: item.roleId,
                  };
                  this.reqRef = requestAnimationFrame(() => {
                    dispatch({
                      type: 'roleManagement/newSysDelRole',
                      payload: roleVo,
                      callback: res => {
                        console.log('删除', res);
                        this.setState({ login: false }, () => {
                          this.newsysgetRolesByCreateUser();
                        });
                      },
                    });
                  });
                }
              },
              onCancel() {
                console.log('onCancel');
              },
            });
          } else {
            console.log(item);
            if (item.roleName === 'admin') {
              message.info(`admin角色不可删除！`);
            } else {
              this.setState({ login: true });
              const roleVo = {
                userId: currentUser.uid,
                roleId: item.roleId,
              };
              this.reqRef = requestAnimationFrame(() => {
                dispatch({
                  type: 'roleManagement/newSysDelRole',
                  payload: roleVo,
                  callback: res => {
                    console.log('删除', res);
                    this.setState({ login: false }, () => {
                      this.newsysgetRolesByCreateUser();
                    });
                  },
                });
              });
            }
          }
        },
      });
    });
  };

  feel = item => {
    console.log(item);
    const { status, createUser } = this.state;
    if (item === 'false') {
      this.setState(
        {
          addModel: false,
        },
        () => {
          this.newsysgetRolesByCreateUser();
          // const { startSetone, startSettwo } = this.state;
          // if (startSetone || startSettwo) {
          //   this.sysGetRoles();
          // } else {
          //   this.newsysgetRolesByCreateUser();
          // }
        }
      );
    }
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { addModelRedact, Redactobj } = this.state;
    const operationDate = [
      {
        title: '序号',
        // dataIndex: 'id',
        align: 'center',
        // width: '100px',
        render: (item, todo, index) => {
          return <span>{this.ceshi(index)}</span>;
        },
      },
      {
        title: '角色名称',
        dataIndex: 'roleName',
        align: 'center',
        // width: '200px',
      },
      {
        title: '状态',
        // width: '100px',
        align: 'center',
        render: (text, item, index) => {
          return (
            <div className="zdyswer">
              <Switch
                onClick={() => {
                  this.rktbonChange(item, index);
                }}
                defaultChecked
                checked={!item.status}
              />
            </div>
          );
        },
      },
      {
        title: '创建人',
        dataIndex: 'createUser',
        align: 'center',
      },
      {
        title: '上次修改时间',
        dataIndex: 'updateTime',
        align: 'center',
        width: 'calc(15vw)',
        render(item) {
          return (
            <div className={styles.hull}>
              <span>{moment(Number(item)).format('YYYY-MM-DD h:mm:ss')}</span>
            </div>
          );
        },
      },
      {
        title: '描述',
        align: 'center',
        // width: '100px',
        dataIndex: 'remakers',
      },
      {
        title: '',
        // width: '250px',
        align: 'center',
        render: (text, item) => {
          return (
            <div className={styles.pb}>
              <div className={styles.tool}>
                <img
                  onClick={() => {
                    this.Redact(item);
                  }}
                  src={bianji}
                />
                <img
                  onClick={() => {
                    this.newSysDelRole(item);
                  }}
                  style={{ marginLeft: 15 }}
                  src={edit}
                />
              </div>
              <img src={moreImg} className={styles.more} />
            </div>
          );
        },
      },
    ];
    return (
      <div>
        <div className={styles.backgroundp}>
          <p style={{ marginLeft: 20, marginTop: 10 }} className="titleA">
            角色管理
          </p>
          <div className={styles.imgbj}>
            <div>
              <Select
                size="large"
                placeholder="状态"
                style={{ width: 200, margin: '0px 20px' }}
                onChange={this.handleChangeSelect}
                defaultValue="全部"
              >
                {this.state.startSetLIst.map((item, index) => {
                  return <Option value={item}>{item}</Option>;
                })}
              </Select>
              {/* <Select
                size="large"
                placeholder="创建人"
                style={{ width: 200, margin: '0px 20px' }}
                onChange={this.handleChangeState}
              >
                {this.state.namelist.map((item, index) => {
                  return <Option value={item}>{item}</Option>;
                })}
              </Select> */}
              <img
                style={{ position: 'relative', top: 3, cursor: 'pointer' }}
                onClick={this.queryList}
                src={query}
              />
            </div>
            <div>
              <img style={{ cursor: 'pointer' }} onClick={this.append} src={append} />
            </div>
          </div>
          <div style={{ height: 20 }} />
          <Spin spinning={this.state.login}>
            <div className={styles.dabj} style={{ padding: '0px 20px' }}>
              <div className={styles.border} style={{ position: 'relative', right: '2px' }}>
                <Table
                  className="zdyTable"
                  columns={operationDate}
                  dataSource={this.state.list} //数据
                  pagination={false}
                />
              </div>
            </div>
            <Pagination
              style={{ textAlign: 'center', marginTop: 20 }}
              total={this.state.total}
              pageSize={this.state.pageSize} // 显示几条一页
              current={this.state.current} // 当前页
              showSizeChanger={true} // 是否显示可以设置几条一页的选项
              onChange={this.onChangeTable}
              onShowSizeChange={this.onShowSizeChangeTable}
              showTotal={() => `共 ${this.state.total} 条`}
            />
          </Spin>
        </div>
        <Drawer
          className="zdyset"
          title={
            <span>
              <Icon
                style={{ cursor: 'pointer' }}
                onClick={this.onClosebj}
                style={{ marginRight: 20 }}
                type="arrow-left"
              />
              {addModelRedact === '1' ? '新增角色' : '编辑角色'}
            </span>
          }
          placement="right"
          closable={false}
          onClose={this.onClosebj}
          visible={this.state.addModel}
          width="calc(100vw - 245px)"
          destroyOnClose
        >
          {addModelRedact === '1' ? (
            <AddRoles feel={this.feel} />
          ) : (
            <RoleCheck feel={this.feel} Redactobj={Redactobj} />
          )}
        </Drawer>
      </div>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(RoleManagement));
